﻿using System;
using System.Collections.Generic;
using System.Text;

namespace AutoAllocService.Map
{
    public class Location
    {
        private static double R = 6378.1;

        public static double CalDisLatitude(double latitude1, double longtitude1, double longitude2)
        {
            latitude1 = (Math.PI / 180.0) * latitude1;
            longtitude1 = (Math.PI / 180.0) * longtitude1;
            longitude2 = (Math.PI / 180.0) * longitude2;

            var temp = Math.Sin(latitude1) * Math.Sin(latitude1) +
                       Math.Cos(latitude1) * Math.Cos(latitude1) * Math.Cos(longitude2 - longtitude1);

            if (temp > 1.0)
                temp = 1.0d;

            var d = Math.Acos(temp) * R;
            return d;
        }

        public static double CalDisLongitude(double latitude1, double latitude2)
        {
            latitude1 = (Math.PI / 180.0) * latitude1;
            latitude2 = (Math.PI / 180.0) * latitude2;

            var temp = Math.Sin(latitude1) * Math.Sin(latitude2) + Math.Cos(latitude1) * Math.Cos(latitude2);

            if (temp > 1.0d)
                temp = 1.0d;

            var d = Math.Acos(temp) * R;
            return d;
        }

        public static double CalDisLongtitudeRe(double latitude1, double longitude1, double d)
        {
            latitude1 = (Math.PI / 180.0) * latitude1;
            longitude1 = (Math.PI / 180.0) * longitude1;

            var temp = Math.Cos(d / R);

            var longitude2 =
                Math.Acos((temp - Math.Sin(latitude1) * Math.Sin(latitude1)) /
                          (Math.Cos(latitude1) * Math.Cos(latitude1))) + longitude1;

            return longitude2 / (Math.PI / 180.0);
        }

        public static double CalDisLatitudeRe(double latitude1, double d)
        {
            var l = 111.321;
            return d / l + latitude1;
        }

        public static (double latitude, double longtitude) CalPointByDis(double latitude, double longitude, double d)
        {
            var l = CalDisLongtitudeRe(latitude, longitude, d);
            l = longitude - (l - longitude);
            var la = CalDisLatitudeRe(latitude, d);
            la = latitude - (la - latitude);

            return (la, l);
        }

        public static ((double latitudeBL, double longitudeBL), (double lattiudeTR, double longtitudeTR)) GetSqrPoints(
            double latitude, double longitude, double d)
        {
            var l = Math.Sqrt(2) / 2 * d;
            var bl = CalPointByDis(latitude, longitude, l);
            var la2 = latitude + (latitude - bl.Item1);
            var longitude2 = longitude + (longitude - bl.Item2);

            var tr = (la2, longitude2);

            return (bl, tr);
        }
    }
}
